package com.vhly.tuite.database;

import android.content.Context;
import android.database.sqlite.*;

import java.util.Enumeration;
import java.util.Hashtable;

/**
 * Created by IntelliJ IDEA.
 * User: vhly
 * Date: 2010-8-2
 * Time: 17:49:52
 *
 * @author vhly[FR]
 */
public class DBHelper extends SQLiteOpenHelper {

    public String tableName = "tweets";
    public static final String ID = "_id";

    private Hashtable<String, String> cols;

    public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        cols = new Hashtable<String, String>();
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public void putCol(String cName, String sqlType){
        if(cName != null && sqlType != null){
            cols.put(cName, sqlType);
        }
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        StringBuffer sb = new StringBuffer("CREATE TABLE IF NOT EXISTS ");
        sb.append(tableName).append(" (").append(ID).append(" INTEGER PRIMARY KEY");
        Enumeration<String> keys = cols.keys();
        while(keys.hasMoreElements()){
            String k = keys.nextElement();
            String v = cols.get(k);
            sb.append(',').append(k).append(' ').append(v);
        }
        sb.append(')');
        String sql =sb.toString();
        sqLiteDatabase.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + tableName);
        onCreate(sqLiteDatabase);
    }
}
